
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react'

interface MessagePaginationProps {
  currentPage: number
  totalPages: number
  pageSize: number
  totalCount: number
  onPageChange: (page: number) => void
  onPageSizeChange: (pageSize: number) => void
  loading?: boolean
}

const PAGE_SIZE_OPTIONS = [50, 100, 200, 500, 1000]

export default function MessagePagination({
  currentPage,
  totalPages,
  pageSize,
  totalCount,
  onPageChange,
  onPageSizeChange,
  loading = false
}: MessagePaginationProps) {
  // 计算显示的页码范围
  const getPageNumbers = () => {
    const delta = 2 // 当前页前后显示的页数
    const range = []
    const rangeWithDots = []

    for (
      let i = Math.max(2, currentPage - delta);
      i <= Math.min(totalPages - 1, currentPage + delta);
      i++
    ) {
      range.push(i)
    }

    if (currentPage - delta > 2) {
      rangeWithDots.push(1, '...')
    } else {
      rangeWithDots.push(1)
    }

    rangeWithDots.push(...range)

    if (currentPage + delta < totalPages - 1) {
      rangeWithDots.push('...', totalPages)
    } else if (totalPages > 1) {
      rangeWithDots.push(totalPages)
    }

    return rangeWithDots
  }

  const startItem = (currentPage - 1) * pageSize + 1
  const endItem = Math.min(currentPage * pageSize, totalCount)

  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages && !loading) {
      onPageChange(page)
    }
  }

  const handlePageSizeChange = (newPageSize: number) => {
    if (!loading) {
      onPageSizeChange(newPageSize)
    }
  }

  if (totalCount === 0) {
    return null
  }

  return (
    <div className="flex items-center justify-between px-4 py-3 bg-white border-t border-gray-200">
      {/* 左侧：显示信息和页面大小选择 */}
      <div className="flex items-center space-x-4">
        <div className="text-sm text-gray-700">
          显示第 <span className="font-medium">{startItem}</span> 到{' '}
          <span className="font-medium">{endItem}</span> 条，共{' '}
          <span className="font-medium">{totalCount}</span> 条记录
        </div>
        
        <div className="flex items-center space-x-2">
          <label htmlFor="pageSize" className="text-sm text-gray-700">
            每页显示:
          </label>
          <select
            id="pageSize"
            value={pageSize}
            onChange={(e) => handlePageSizeChange(Number(e.target.value))}
            disabled={loading}
            className="border border-gray-300 rounded-md px-2 py-1 text-sm focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {PAGE_SIZE_OPTIONS.map((size) => (
              <option key={size} value={size}>
                {size} 条
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* 右侧：分页控件 */}
      <div className="flex items-center space-x-1">
        {/* 第一页 */}
        <button
          onClick={() => handlePageChange(1)}
          disabled={currentPage === 1 || loading}
          className="p-2 rounded-md border border-gray-300 bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          title="第一页"
        >
          <ChevronsLeft className="h-4 w-4" />
        </button>

        {/* 上一页 */}
        <button
          onClick={() => handlePageChange(currentPage - 1)}
          disabled={currentPage === 1 || loading}
          className="p-2 rounded-md border border-gray-300 bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          title="上一页"
        >
          <ChevronLeft className="h-4 w-4" />
        </button>

        {/* 页码 */}
        <div className="flex items-center space-x-1">
          {getPageNumbers().map((pageNumber, index) => {
            if (pageNumber === '...') {
              return (
                <span
                  key={`dots-${index}`}
                  className="px-3 py-2 text-gray-500"
                >
                  ...
                </span>
              )
            }

            const page = pageNumber as number
            const isCurrentPage = page === currentPage

            return (
              <button
                key={page}
                onClick={() => handlePageChange(page)}
                disabled={loading}
                className={`
                  px-3 py-2 rounded-md border text-sm font-medium transition-colors
                  ${isCurrentPage
                    ? 'border-primary-500 bg-primary-50 text-primary-600'
                    : 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
                  }
                  disabled:opacity-50 disabled:cursor-not-allowed
                `}
              >
                {page}
              </button>
            )
          })}
        </div>

        {/* 下一页 */}
        <button
          onClick={() => handlePageChange(currentPage + 1)}
          disabled={currentPage === totalPages || loading}
          className="p-2 rounded-md border border-gray-300 bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          title="下一页"
        >
          <ChevronRight className="h-4 w-4" />
        </button>

        {/* 最后一页 */}
        <button
          onClick={() => handlePageChange(totalPages)}
          disabled={currentPage === totalPages || loading}
          className="p-2 rounded-md border border-gray-300 bg-white text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          title="最后一页"
        >
          <ChevronsRight className="h-4 w-4" />
        </button>

        {/* 页面跳转 */}
        <div className="flex items-center space-x-2 ml-4">
          <span className="text-sm text-gray-700">跳转到:</span>
          <input
            type="number"
            min={1}
            max={totalPages}
            placeholder="页码"
            disabled={loading}
            className="w-16 px-2 py-1 border border-gray-300 rounded-md text-sm text-center focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
            onKeyPress={(e) => {
              if (e.key === 'Enter') {
                const target = e.target as HTMLInputElement
                const page = parseInt(target.value)
                if (page >= 1 && page <= totalPages) {
                  handlePageChange(page)
                  target.value = ''
                }
              }
            }}
          />
        </div>
      </div>

      {/* 加载状态 */}
      {loading && (
        <div className="absolute inset-0 bg-white bg-opacity-50 flex items-center justify-center">
          <div className="flex items-center space-x-2">
            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary-600"></div>
            <span className="text-sm text-gray-600">加载中...</span>
          </div>
        </div>
      )}
    </div>
  )
}

// 快速跳转组件
export function QuickJumpPagination({
  currentPage,
  totalPages,
  onPageChange,
  loading = false
}: {
  currentPage: number
  totalPages: number
  onPageChange: (page: number) => void
  loading?: boolean
}) {
  const handleQuickJump = (direction: 'start' | 'end' | 'middle') => {
    if (loading) return

    switch (direction) {
      case 'start':
        onPageChange(1)
        break
      case 'end':
        onPageChange(totalPages)
        break
      case 'middle':
        onPageChange(Math.ceil(totalPages / 2))
        break
    }
  }

  return (
    <div className="flex items-center space-x-2 text-sm">
      <span className="text-gray-600">快速跳转:</span>
      <button
        onClick={() => handleQuickJump('start')}
        disabled={currentPage === 1 || loading}
        className="px-2 py-1 text-primary-600 hover:text-primary-800 disabled:opacity-50 disabled:cursor-not-allowed"
      >
        最新
      </button>
      <span className="text-gray-300">|</span>
      <button
        onClick={() => handleQuickJump('middle')}
        disabled={loading}
        className="px-2 py-1 text-primary-600 hover:text-primary-800 disabled:opacity-50 disabled:cursor-not-allowed"
      >
        中间
      </button>
      <span className="text-gray-300">|</span>
      <button
        onClick={() => handleQuickJump('end')}
        disabled={currentPage === totalPages || loading}
        className="px-2 py-1 text-primary-600 hover:text-primary-800 disabled:opacity-50 disabled:cursor-not-allowed"
      >
        最早
      </button>
    </div>
  )
}
